package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.form.modules.engin.base.formData.FormDataDAO;

import com.seeyon.apps.shangqi.util.MessageKit;
import com.seeyon.apps.shangqi.util.StrKit;
import org.apache.commons.logging.Log;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Path("shangqi")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public class CustomFormDataStateResources extends BaseResource {
    private static final Log log = CtpLogFactory.getLog(CustomFormDataStateResources.class);
    private String localAddr = AppContext.getRawRequest().getLocalAddr();
    private String port = String.valueOf(AppContext.getRawRequest().getLocalPort());
    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private static FormDataDAO formDataDAO = (FormDataDAO) AppContext.getBean("formDataDAO");
    private static final String fkUnFlowTemplateCode = AppContext.getSystemProperty("ndk.fkUnFlowTemplateCode");
    /**
     * 更新表单数据状态
     *
     * @param param 包含表单数据状态更新信息的Map
     * @return 返回操作结果的Response对象
     */
    @POST
    @Path("updateFormDataStateNew")
    public Response updateFormDataState(Map<String, Object> param) throws Exception {
        String dataJson = JSON.toJSONString(param);
        log.info("主数据平台调用接口入参json:" + dataJson);
//        ErrorKit.addLog("主数据平台调用接口入参json：" + dataJson, CustomFormDataStateResources.class.getName());
        JSONObject jsonObj = new JSONObject(param);
        //OA系统单号
        String OACODE = "";
        //凭证字
        String TEXT = "";
        //凭证号
        String num = "";
        //凭证日期
        String date = "";
        //status
        String status = "";
        //EXT1扩展
        String EXT1 = "";
        //summaryId
      //  String summaryId = "";
        log.info("回调接口拿到的参数为"+param);
        StringBuilder stb = new StringBuilder();
        if (jsonObj.containsKey("data")) {
            JSONArray jsonArray = jsonObj.getJSONArray("data");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    OACODE =   (String)  jsonObject.get("OACODE");
//                    TEXT =   (String)  jsonObject.get("TEXT");
//                    date =   (String)  jsonObject.get("date");
//                    num =   (String)  jsonObject.get("num");
//                    EXT1 =   (String)  jsonObject.get("EXT");
//                    status =   (String)  jsonObject.get("status");


                    OACODE = StrKit.str(jsonObject.get("OACODE"));
                    TEXT = StrKit.str(jsonObject.get("TEXT"));
                    status = StrKit.str(jsonObject.get("status"));
                    date = StrKit.str(jsonObject.get("date"));
                  //  stb.append(StrKit.str(jsonObject.get("MSG")));
                    num = StrKit.str(jsonObject.get("num"));
                    EXT1 = StrKit.str(jsonObject.get("EXT1"));
                }
//                 summaryId = StrKit.str(jsonObj.get("summaryId"));
             //    summaryId = (String)jsonObj.get("summaryId");

            }

        } else {
            Map<String, Object> msgMap = MessageKit.errorMsg("1", "data无数据请检查传参", "占位符");
            return ok(JSON.toJSON(msgMap));
        }
        try {
        //成功与否
       //  status = StrKit.str(jsonObj.get("status"));
        Long memberId = null;
        String formCode = "";

            // 检查guid是否为空
            if ("".equals(EXT1)) {
                Map<String, Object> msgMap = MessageKit.errorMsg("1", "EXT1不能为空值", EXT1);
                return ok(JSON.toJSON(msgMap));
            }
            // 处理guid格式数据，更新表单状态
            if (EXT1.contains("_")) {
                String dataId = EXT1.split("_")[0];

                String templateCode = EXT1.split("_")[1];
                FormBean formBean = cap4FormManager.getFormByFormCode(templateCode);
                // 检查模版编码是否存在
                if (formBean == null) {
                    Map<String, Object> msgMap = MessageKit.errorMsg("1", "模版编码不存在，请找OA负责人，系统未找到对应的OA单据!", EXT1);
                    return ok(JSON.toJSON(msgMap));
                }
                FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(Long.parseLong(dataId), formBean, null);
                if (formDataMasterBean == null) {
                    Map<String, Object> msgMap = MessageKit.errorMsg("1", "EXT1[" + EXT1 + "]有误,系统中未找到该合同!", EXT1);
                    return ok(JSON.toJSON(msgMap));
                }
                memberId = formDataMasterBean.getStartMemberId();
                // 根据类型更新不同的字段值
                String pzh_fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("凭证号").getName();
                String pzrq_fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("凭证日期").getName();

                List<String> fieldList = new ArrayList<String>();

                formDataMasterBean.addFieldValue(pzh_fieldName,TEXT+"-"+num);
                fieldList.add(pzh_fieldName);

                //日期
              //  SimpleDateFormat simpleDateFormat=new SimpleDateFormat();
                Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);

                formDataMasterBean.addFieldValue(pzrq_fieldName,date1);
                fieldList.add(pzrq_fieldName);
                // 保存或更新表单数据
                cap4FormManager.saveOrUpdateFormData(formDataMasterBean, formBean.getId(), true, fieldList);
                Map<String, Object> msgMap = MessageKit.errorMsg("0", "更新状态成功", EXT1);
                return ok(JSON.toJSON(msgMap));
            }
        } catch (Exception e) {
            log.error("更新表单状态失败", e);
            String errorMsg = "更新表单状态失败:" + e.getMessage();
            Map<String, Object> msgMap = MessageKit.errorMsg("1", errorMsg, EXT1);
            return ok(JSON.toJSON(msgMap));
        }
        return null;
    }


}